﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>

    <link href="site.css" rel="stylesheet" />
    <script src="jquery.js"></script>

    <style type="text/css">
        .video {
            width: 80%;
            height: 60%;
        }
    </style>

    <script type="text/javascript">
        let baseUrl = "http://127.0.0.1:8080/";

        function showRet(ret, status) {
            let ele = document.getElementById("divRet");
            if (ret.Data) {
                ele.innerText = ret.Data + ret;
            }
            else {
                ele.innerText = "status:" + status + "\r\n" + ret;
            }
        }

        function showErrRet(err) {
            document.getElementById("divRet").innerText = "错误信息:" + err.statusText;
        }

        function getReqHeaders() {
            let headers =
            {
                //keysConstant.token: tokenInfo.token //不能这样写,必须写成死字符串
                "token": "XXX123YY+-",
                "uid": 1
            };

            return headers;
        }




        let _websocket = null;
        function _closeWebsocket() {
            if (_websocket == null) {
                return;
            }

            _websocket.close();
            //_websocket.onopen = null;
            //_websocket.onmessage = null;
            //_websocket.onclose = null;
            //_websocket.onerror = null;
            //_websocket = null;
        }

        function _createWebSocket() {
            _closeWebsocket();

            var url;
            if (window.document.location.origin.startsWith("https://")) {
                url = window.document.location.origin.replace("https://", "wss://") + "/posture";
            }
            else {
                url = window.document.location.origin.replace("http://", "ws://") + "/posture";
            }

            //ws://localhost:5280/posture
            url = "ws://127.0.0.1:8080/posture";
            let webSocket = new WebSocket(url);
            //webSocket = new WebSocket(config.instance.websocketUrl);
            webSocket.onopen = function (e) {
                showRet('webSocket connection opened .', "onopen")
            };

            webSocket.onmessage = function (e) {
                if (e.data instanceof Blob) {
                    //websoket服务端发送二进制数据处理方式
                    var reader = new FileReader()
                    reader.addEventListener('loadend', function (er) {
                        let view = new DataView(er.target.result);
                        let littleEndian = true
                        let index = 0;

                        let id = view.getInt32(index, littleEndian);
                        index += 4;

                        let contentLen = view.getInt32(index, littleEndian);
                        index += 4;

                        let arrBuffer = new ArrayBuffer(contentLen);
                        let arrBufferView = new DataView(arrBuffer);
                        let tmp;
                        for (let i = 0; i < contentLen; i++) {
                            tmp = view.getUint8(index, littleEndian);
                            arrBufferView.setUint8(i, tmp, littleEndian)
                            index++;
                        }
                        const decoder = new TextDecoder("utf-8");
                        const str = decoder.decode(arrBuffer);
                        showRet(str, "blob11");
                    })
                    reader.readAsArrayBuffer(e.data)
                }
                else {
                    showRet(e.data, "onmessage")
                }
            };

            webSocket.onclose = function (e) {
                showRet('Connection closed.' + e.code + ' ' + e.reason, "onclose")
            };

            webSocket.onerror = function (e) {
                showRet(e, "onerror")
            };

            _websocket = webSocket;
        }



        function testWebsocket() {
            _createWebSocket();
        }

        function testDisWebsocket() {
            _closeWebsocket();
        }

        function testWebsocketSendData() {
            let msg = {
                type: 123,
                body: "abc夜风+ -/*"
            };

            let json = JSON.stringify(msg);
            _websocket.send(json);
        }

        function testWebsocketPing() {
            _websocket.ping();
        }






        function testApiGet(index) {
            let url;
            switch (index) {
                case 0:
                    url = baseUrl + "testApi";
                    break;
                case 1:
                    url = baseUrl + "testApi/getName";
                    break;
                case 2:
                    url = baseUrl + "testApi/test?min=123&max=456";
                    break;
                case 3:
                    url = baseUrl + "testApi/6/10/50.png";
                    break;
                case 4:
                    url = baseUrl + "testApi/abc6/gg10mm/kk/50.png";
                    break;
                case 5:
                    url = baseUrl + "testApi/123夜风.dat";
                    break;
                case 6:
                    url = baseUrl + "testApi/mix/3/gg2mm/kk/1.png?min=132&max=456";
                    break;
                default:
                    showErrRet({ statusText: "未知的索引" });
                    return;
            }


            //$.ajax({
            //    type: "GET",
            //    url: url,
            //    async: true,
            //    headers: getReqHeaders(),
            //    contentType: "application/json; charset=utf-8",
            //    //dataType: "json",
            //    success: showRet,
            //    error: showErrRet
            //});

            //原生js get请求
            let xhr = new XMLHttpRequest();
            xhr.open("get", url, true);
            xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        let ret = JSON.parse(xhr.responseText);
                        showRet(ret, xhr.status);
                    }
                    else {
                        showRet("", xhr.responseText);
                    }
                }
            };
            xhr.send(null);
        }

        function testApiPost(index) {
            let url;
            switch (index) {
                case 0:
                    url = baseUrl + "testApi";
                    break;
                case 1:
                    url = baseUrl + "testApi/test?min=123&max=465";
                    break;
                default:
                    showErrRet({ statusText: "未知的索引" });
                    return;
            }

            let data = {};
            data.id = 12;
            data.name = "yf夜风";
            data.age = 23;
            let json = JSON.stringify(data);
            //json = '{\"id\":12,\"name\":\"yf夜风\",\"age\":23';
            //$.ajax({
            //    type: "POST",
            //    url: url,
            //    data: json,
            //    async: true,
            //    contentType: "application/json; charset=utf-8",
            //    //dataType: "json",
            //    headers: getReqHeaders(),
            //    success: showRet,
            //    error: showErrRet
            //});

            //原生js post请求
            let xhr = new XMLHttpRequest();
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        let ret = JSON.parse(xhr.responseText);
                        showRet(ret, xhr.status);
                    }
                    else {
                        showRet("", xhr.responseText);
                    }
                }
            };
            xhr.send(json);
        }

        function testApiPut(index) {
            let url;
            switch (index) {
                case 0:
                    url = baseUrl + "testApi";
                    break;
                case 1:
                    url = baseUrl + "testApi?id=234";
                    break;
                default:
                    showErrRet({ statusText: "未知的索引" });
                    return;
            }

            let data = {};
            data.id = 12;
            data.name = "yf夜风2";
            data.age = 25;
            let json = JSON.stringify(data);
            $.ajax({
                type: "PUT",
                url: url,
                data: json,
                async: true,
                contentType: "application/json; charset=utf-8",
                //dataType: "json",
                headers: getReqHeaders(),
                success: showRet,
                error: showErrRet
            });
        }

        function testApiDelete(index) {
            let url;
            switch (index) {
                case 0:
                    url = baseUrl + "testApi/Delete?id=111";
                    break;
                case 1:
                    url = baseUrl + "testApi/delete2?id=222";
                    break;
                default:
                    showErrRet({ statusText: "未知的索引" });
                    return;
            }

            $.ajax({
                type: "DELETE",
                url: url,
                async: true,
                headers: getReqHeaders(),
                contentType: "application/json; charset=utf-8",
                //dataType: "json",
                success: showRet,
                error: showErrRet
            });
        }

        function testApiExtend() {
            let url = baseUrl + "testApi";
            let data = {};
            data.id = 12;
            data.name = "yf夜风";
            data.age = 23;
            let json = JSON.stringify(data);

            $.ajax({
                type: "Extension-mothed",
                url: url,
                data: json,
                async: true,
                headers: getReqHeaders(),
                contentType: "application/json; charset=utf-8",
                //dataType: "json",
                success: showRet,
                error: showErrRet
            });
        }


        let cookie = null;
        function login() {
            let url = baseUrl + "testApi/login?uid=yf&pwd=qew123";
            $.ajax({
                type: "GET",
                url: url,
                async: true,
                headers: getReqHeaders(),
                contentType: "application/json; charset=utf-8",
                //dataType: "json",
                success: function (ret, status) {
                    showRet(ret, status);
                    if (ret.status == 1) {
                        cookie = ret.data;
                    }
                },
                error: showErrRet
            });
        }

        function getAuthData() {
            let url = baseUrl + "testApi/getAuthData?id=23";
            var headers = getReqHeaders();
            headers["Cookie"] = cookie;
            $.ajax({
                type: "GET",
                url: url,
                async: true,
                headers: headers,
                contentType: "application/json; charset=utf-8",
                //dataType: "json",
                success: function (ret, status) {
                    showRet(ret, status);
                },
                error: showErrRet
            });
        }


        function rbf() {
            var audio = document.getElementById("audioMusic"); //必须用原生js获取id，jquery无效
            audio.currentTime = 0;
        }

        function bf() {
            var audio = document.getElementById("audioMusic");  //必须用原生js获取id，jquery无效
            if (audio !== null) {
                //检测播放是否已暂停.audio.paused 在播放器播放时返回false.
                //alert(audio.paused);
                if (audio.paused) {
                    audio.play();//audio.play();// 这个就是播放
                } else {
                    audio.pause();// 这个就是暂停
                }
            }
        }


        /**
        * http-post 上传文件
        */
        function testJqueryBuildFormDtaUploadFile() {
            let inputMarkerImageEle = document.getElementById("inputMarkerImage");
            inputMarkerImageEle.value = "";//清空前一次选择的文件
            inputMarkerImageEle.click();
        }

        function chioceMarkerImageChanged(sender) {
            let url = baseUrl + "testApi/uploadFile";
            var formData = new FormData();
            // HTML 文件类型input，由用户选择
            for (let file of sender.files) {
                formData.append(file.name, file);
            }

            $.ajax({
                type: "POST",
                url: url,
                data: formData,
                async: true,
                contentType: false,//值只能填写false，不能用form的值"multipart/form-data",否则jquery内部会作些处理，就会缺少字段
                processData: false,
                headers: getReqHeaders(),
                success: showRet,
                error: showErrRet
            });
        }



        function testJqueryFormDataUploadFile() {
            var formData = new FormData($("#uploadForm")[0]);
            let url = baseUrl + "testApi/uploadFile";
            $.ajax({
                type: "POST",
                url: url,
                data: formData,
                async: true,
                contentType: false,//值只能填写false，不能用form的值"multipart/form-data",否则jquery内部会作些处理，就会缺少字段
                processData: false,
                headers: getReqHeaders(),
                success: showRet,
                error: showErrRet
            });
        }
    </script>
</head>
<body>
    <button onclick="testWebsocket()">websocket</button>
    <button onclick="testDisWebsocket()">disWebsocket</button>
    <button onclick="testWebsocketSendData()">SendData</button>
    <button onclick="testWebsocketPing()">Ping</button>
    <hr />
    <button onclick="testApiGet(0)">ApiGet-testApi</button>
    <button onclick="testApiGet(1)">ApiGet-testApi/getName</button>
    <button onclick="testApiGet(2)">ApiGet-testApi/test?min=123&max=456</button>
    <button onclick="testApiGet(3)">ApiGet-testApi/6/10/50.png</button>
    <button onclick="testApiGet(4)">ApiGet-testApi/abc6/gg10mm/kk/50.png</button>
    <button onclick="testApiGet(5)">ApiGet-testApi/123夜风.dat</button>
    <button onclick="testApiGet(6)">ApiGet-testApi/mix</button>
    <hr />
    <button onclick="testApiPost(0)">ApiPost-testApi</button>
    <button onclick="testApiPost(1)">ApiPost-testApi/test?min=123&max=465</button>
    <hr />
    <button onclick="testApiPut(0)">ApiPut-testApi</button>
    <button onclick="testApiPut(1)">ApiPut-testApi?id=234</button>
    <hr />
    <button onclick="testApiDelete(0)">ApiDelete-testApi/Delete?id=111</button>
    <button onclick="testApiDelete(1)">ApiDelete-testApi/delete2?id=222</button>
    <hr />
    <button onclick="testApiExtend()">ApiExtend</button>
    <button onclick="login()">Login</button>
    <button onclick="getAuthData()">GetAuthData</button>
    <hr />
    <button onclick="testJqueryBuildFormDtaUploadFile()">jquery构造FormData上传文件</button>
    <input title="png文件" id="inputMarkerImage" accept=".png,.jpg,jpeg,.bmp,.gif,.ico" type="file" multiple="multiple" style="display:none" onchange="chioceMarkerImageChanged(this)">
    <hr />
    <form id="uploadForm" method="POST" action="testApi/uploadFile" enctype="multipart/form-data">
        <!--单文件-->
        <!--<input type="file" name="file" value="请选择文件"><br />-->
        <!--多文件-->
        <input type="file" name="file" multiple="multiple" value="请选择文件"><br />
        <input type="submit" value="form直接提交上传文件" />
    </form>
    <button onclick="testJqueryFormDataUploadFile()">jquery引用formdata上传文件</button>
    <hr />
    <a href="元日.mp4">元日</a>
    <br />
    <a href="abc第一期.pdf">abc第一期.pdf</a>
    <br />
    <a href="输入法\sogou_wubi_31a.exe">sogou_wubi_31a.exe</a>
    <br />
    <img src="Desert.jpg" style="height:100px;width:auto" />
    <hr />
    <div>
        <p>天不下雨,天不刮风,天上有太阳,妹不开口,妹不说话,妹心怎么想!</p>
        <span>bay_bay_bay.mp3</span>
        <button onclick="bf()">播放/暂停</button>
        <button onclick="rbf()">重新播放</button>
        <audio id="audioMusic" loop="loop" autoplay="autoplay">
            <source src="bay_bay_bay.mp3" type="audio/mpeg">
        </audio>
    </div>
    <hr />
    <!--<video class="video" controls="controls">
        <source src="过年.MP4" type="video/mp4" />
    </video>
    <hr />-->
    <div id="divRet">

    </div>
</body>
</html>
